package com.paipaideli.ui.login;

import android.content.Context;
import android.content.Intent;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding2.view.RxView;
import com.paipaideli.R;
import com.paipaideli.common.base.BasePresenterActivity;
import com.paipaideli.common.http.Api;
import com.paipaideli.common.pullrefresh.TStatusView;
import com.paipaideli.common.utils.JsutmentUtil;
import com.paipaideli.common.utils.StringUtil;
import com.paipaideli.common.utils.ToastUtil;
import com.paipaideli.common.utils.preferrnces.FastData;
import com.paipaideli.ui.MainActivity;
import com.paipaideli.ui.mine.safety.ForgetPwdActivity;

import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by 登录页面
 */
public class LoginActivity extends BasePresenterActivity {

    Unbinder unbinder;
    @BindView(R.id.login_phone)
    EditText login_phone;
    @BindView(R.id.login_pwd)
    EditText login_pwd;
    @BindView(R.id.rel_see)
    RelativeLayout rel_see;
    @BindView(R.id.image_pwd)
    ImageView image_pwd;
    @BindView(R.id.login_rem_pwd)
    RelativeLayout login_rem_pwd;
    @BindView(R.id.login_image_rem)
    ImageView login_image_rem;
    @BindView(R.id.login_register)
    TextView login_register;
    @BindView(R.id.login_forgetpwd)
    TextView login_forgetpwd;
    @BindView(R.id.btn_login)
    Button btn_login;
    @BindView(R.id.bg_statusview)
    TStatusView bg_statusview;

    private String pwd;
    boolean isRememberPwd;

    public static void open(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);
    }

    @Override
    public int getContentView() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        unbinder = ButterKnife.bind(this);

        String username = FastData.getUsername();
        String userPwd = FastData.getUserPwd();
        if (JsutmentUtil.isMobileTrue(username)) {
            login_phone.setText(username);
        }
        isRememberPwd = FastData.getIsRememberPwd();
        if (isRememberPwd) {
            login_pwd.setText(userPwd);
            isRememberPwd = true;
            FastData.setIsRememberPwd(true);
            login_image_rem.setImageResource(R.mipmap.login_check);
        } else {
            login_pwd.setText("");
            isRememberPwd = false;
            FastData.setIsRememberPwd(false);
            login_image_rem.setImageResource(R.mipmap.login_nocheck);
        }

        //查看密码
        RxView.clicks(rel_see)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
            seePwd();
        }, throwable -> {
        });

        //记住密码
        RxView.clicks(login_rem_pwd)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    rememberPwd();
                }, throwable -> {
                });

        //去登录
        addDisposable(RxView.clicks(btn_login)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    Login();
                }));

        //快速注册
        RxView.clicks(login_register)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                    startActivity(intent);
                }, throwable -> {
                });

        //忘记密码
        RxView.clicks(login_forgetpwd)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    Intent intent = new Intent(LoginActivity.this, ForgetPwdActivity.class);
                    startActivity(intent);
                }, throwable -> {
                });
    }

    //隐藏显示密码
    private void seePwd() {
        pwd = login_pwd.getText().toString().trim();
        if (!StringUtil.isEmpty(pwd)) {
            TransformationMethod type = login_pwd.getTransformationMethod();
            if (PasswordTransformationMethod.getInstance().equals(type)) {
                login_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                image_pwd.setBackgroundResource(R.mipmap.login_look);
            } else {
                login_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                image_pwd.setBackgroundResource(R.mipmap.login_unlook);
            }
        }
    }

    //记住密码
    private void rememberPwd() {
        if (isRememberPwd) {
            isRememberPwd = false;
            FastData.setIsRememberPwd(false);
            login_image_rem.setImageResource(R.mipmap.login_nocheck);
        } else {
            isRememberPwd = true;
            FastData.setIsRememberPwd(true);
            login_image_rem.setImageResource(R.mipmap.login_check);
        }
    }

    //登录操作
    private void Login() {
        String phone = login_phone.getText().toString().trim();
        String pwd = login_pwd.getText().toString().trim();
        if (!StringUtil.isEmpty(phone)) {
            if (JsutmentUtil.isMobileTrue(phone)) {
                if (!StringUtil.isEmpty(pwd)) {
                    JSONObject requestData = new JSONObject();
                    try {
                        requestData.put("phone", phone);
                        requestData.put("password", pwd);
                    } catch (Exception e) {
                        e.getMessage();
                    }
                    RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
                    bg_statusview.showLoading();
                    Api.getInstanceGson().login(body)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(request -> {
                                if (request.code.equals("200")) {
                                    FastData.setUsername(phone);
                                    FastData.setUserPwd(pwd);
                                    FastData.setReferralCode(request.data.referralCode);
                                    FastData.setToken(request.data.token);

                                    FastData.setIsLogin(true);
                                    MainActivity.openSingleTop(getCurrentActivity());
                                    finish();
                                    bg_statusview.finish();
                                    ToastUtil.show(request.msg);
                                } else {
                                    bg_statusview.finish();
                                    ToastUtil.show(request.msg);
                                }
                            }, throwable -> {
                                bg_statusview.finish();
                            });
                } else {
                    ToastUtil.show("请输入密码！");
                }
            } else {
                ToastUtil.show("请输入正确的手机号码");
            }
        } else {
            ToastUtil.show("请输入手机号码");
        }
    }
}
